package com.orange.off.cloud.cloudoff.fragments;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.RegisteredEvent;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.ProgressDlgUtil;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;
import com.orange.off.cloud.cloudoff.views.CountDownButtonHelper;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 注册
 *
 * @author smile
 */
public class RegisteredFragment extends Fragment {


    @Bind(R.id.common_back)
    RelativeLayout commonBack;
    @Bind(R.id.registered_phone)
    EditText registeredPhone;
    @Bind(R.id.registered_phone_clear)
    ImageView registeredPhoneClear;
    @Bind(R.id.registered_pwd1)
    EditText registeredPwd1;
    @Bind(R.id.registered_pwd1_clear)
    ImageView registeredPwd1Clear;
    @Bind(R.id.registered_pwd2)
    EditText registeredPwd2;
    @Bind(R.id.registered_pwd2_clear)
    ImageView registeredPwd2Clear;
    @Bind(R.id.registered_code)
    EditText registeredCode;
    @Bind(R.id.registered_code_btn)
    Button registeredCodeBtn;
    @Bind(R.id.registered_submit_button)
    Button registeredSubmitButton;
    @Bind(R.id.registered_name)
    EditText registeredName;
    @Bind(R.id.registered_name_clear)
    ImageView registeredNameClear;

    public static RegisteredFragment newInstance() {
        RegisteredFragment fragment = new RegisteredFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    private SharedPreferences mPreferences;
    private CountDownButtonHelper helper;
    private Boolean isTimer = false;
    private String code = "";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.registered_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    private void initViews() {
        mPreferences = getActivity().getSharedPreferences("user_info", 0);
        registeredPhone.addTextChangedListener(phoneTextWatcher);
        registeredName.addTextChangedListener(nameTextWatcher);
        registeredPwd1.addTextChangedListener(pwdTextWatcher1);
        registeredPwd2.addTextChangedListener(pwdTextWatcher2);

    }


    @OnClick({R.id.common_back, R.id.registered_phone_clear, R.id.registered_pwd1_clear
            , R.id.registered_pwd2_clear, R.id.registered_code_btn, R.id.registered_submit_button, R.id.registered_name_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                if (isTimer) {
                    helper.close();
                }
                getActivity().finish();
                break;
            case R.id.registered_phone_clear:
                registeredPhone.setText("");
                break;
            case R.id.registered_name_clear:
                registeredName.setText("");
                break;
            case R.id.registered_pwd1_clear:
                registeredPwd1.setText("");
                break;
            case R.id.registered_pwd2_clear:
                registeredPwd2.setText("");
                break;
            case R.id.registered_code_btn:
                registeredCodeBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.registered_code_down));
                helper = new CountDownButtonHelper(registeredCodeBtn, "重新获取", 60, 1);
                helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() {

                    @Override
                    public void finish() {
                        registeredCodeBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.registered_code_on));
                    }
                });
                helper.start();
                isTimer = true;
                getCode();
                break;
            case R.id.registered_submit_button:
                final String phone = registeredPhone.getText().toString().trim();
                final String name = registeredName.getText().toString().trim();
                final String Pwd1 = registeredPwd1.getText().toString().trim();
                final String Pwd2 = registeredPwd2.getText().toString().trim();
                String VerificationCode = registeredCode.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.show(getActivity(), "请输入有效手机号！");
                    return;
                }
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.show(getActivity(), "请输入您的姓名！");
                    return;
                }
                if (TextUtils.isEmpty(Pwd1)) {
                    ToastUtils.show(getActivity(), "请输入密码！");
                    return;
                }
                if (TextUtils.isEmpty(Pwd2)) {
                    ToastUtils.show(getActivity(), "请再次输入密码！");
                    return;
                }
                if (!Pwd1.equals(Pwd2)) {
                    ToastUtils.show(getActivity(), "两次密码不相同，请再次输入！");
                    return;
                }
                if (!Pwd1.equals(Pwd2)) {
                    ToastUtils.show(getActivity(), "两次密码不相同，请再次输入！");
                    return;
                }
                if (TextUtils.isEmpty(VerificationCode)) {
                    ToastUtils.show(getActivity(), "请输入验证码！");
                    return;
                }
                if (!code.equals(VerificationCode)) {
                    ToastUtils.show(getActivity(), "验证码输入错误，请确认短信！");
                    return;
                }
                ProgressDlgUtil.showProgressDlg("注册中，请稍后...", getActivity());
                registeredSubmitButton.setEnabled(false);
                RequestParams params = new RequestParams();
                params.addFormDataPart("account", phone);
                params.addFormDataPart("mima", Pwd2);
                params.addFormDataPart("name", name);
                params.addFormDataPart("code", VerificationCode);
                HttpRequest.post(AppUrls.Registered, params, new BaseHttpRequestCallback<UploadResponse>() {
                    @Override
                    public void onSuccess(UploadResponse uploadResponse) {
                        super.onSuccess(uploadResponse);
                        ProgressDlgUtil.stopProgressDlg();
                        registeredSubmitButton.setEnabled(true);
                        if (uploadResponse.getSuccess()) {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                            EventBus.getDefault().post(new RegisteredEvent(phone, Pwd2));
                            getActivity().finish();
                        } else {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                        }

                    }

                    @Override
                    public void onFailure(int errorCode, String msg) {
                        super.onFailure(errorCode, msg);
                        ProgressDlgUtil.stopProgressDlg();
                        registeredSubmitButton.setEnabled(true);
                    }

                    @Override
                    public void onProgress(int progress, long networkSpeed, boolean done) {
                    }
                });
                break;
        }
    }

    void getCode() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("phone", registeredPhone.getText().toString().trim());
        HttpRequest.post(AppUrls.VerificationCode, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                Log.d(MyApplication.DEBUG, "getcode---》" + uploadResponse.toString());

                if (uploadResponse.getSuccess()) {
                    code = uploadResponse.getCode();
                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    TextWatcher phoneTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!registeredPhone.getText().toString().equals("")) {
                registeredPhoneClear.setVisibility(View.VISIBLE);
            } else {
                registeredPhoneClear.setVisibility(View.INVISIBLE);
            }
        }
    };
    TextWatcher nameTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!registeredName.getText().toString().equals("")) {
                registeredNameClear.setVisibility(View.VISIBLE);
            } else {
                registeredNameClear.setVisibility(View.INVISIBLE);
            }
        }
    };

    TextWatcher pwdTextWatcher1 = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!registeredPwd1.getText().toString().equals("")) {
                registeredPwd1Clear.setVisibility(View.VISIBLE);
            } else {
                registeredPwd1Clear.setVisibility(View.INVISIBLE);
            }
        }
    };
    TextWatcher pwdTextWatcher2 = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!registeredPwd2.getText().toString().equals("")) {
                registeredPwd2Clear.setVisibility(View.VISIBLE);
            } else {
                registeredPwd2Clear.setVisibility(View.INVISIBLE);
            }
        }
    };


    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isTimer) {
                helper.close();
            }
            getActivity().finish();
            return true;
        }
        return false;
    }


}
